package cn.achao.csr.system.dao;

import cn.achao.csr.api.model.entity.SysUser;
import cn.achao.csr.api.model.entity.SysUserExpand;
import cn.achao.csr.base.constant.enums.SysSourceEnum;
import cn.achao.csr.base.exception.BusinessException;
import cn.achao.csr.base.utils.ThrowUtils;
import cn.achao.csr.system.mapper.SysUserExpandMapper;
import cn.achao.csr.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: achao
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserDao extends ServiceImpl<SysUserMapper, SysUser> {

    private final SysUserMapper userMapper;
    private final SysUserExpandMapper userExpandMapper;

    public SysUser selectUserByUserAccount(String userAccount) {
        return userMapper.selectUserByUserAccount(userAccount);
    }

    public SysUser selectUserByZfbOpenId(String openId) {
        SysUserExpand sysUserExpand = userExpandMapper.selectOne(
                new QueryWrapper<SysUserExpand>()
                        .lambda().eq(SysUserExpand::getZfbId, openId).last("limit 1").select(SysUserExpand::getId)
        );

        ThrowUtils.throwIf(sysUserExpand == null,
                BusinessException.fail("支付宝用户不存在", SysSourceEnum.CSR_SYSTEM.getSysName()));

        SysUser sysUser = selectOneByEId(sysUserExpand.getId());
        sysUser.setUserExpand(sysUserExpand);
        return sysUser;
    }

    public SysUser selectOneByEId(Long ExpandId) {
        SysUser sysUser = userMapper.selectOneByEId(ExpandId);
        ThrowUtils.throwIf(sysUser == null,
                BusinessException.fail("用户不存在", SysSourceEnum.CSR_SYSTEM.getSysName()));
        return sysUser;
    }

    public boolean isExistAccount(String userAccount) {
        return userMapper.selectCount(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserAccount, userAccount)) > 0;
    }

    public Map<Long, SysUser> getBatchByIds(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new HashMap<>();
        }

        return lambdaQuery()
                .in(SysUser::getId, userIds)
                // 添加列表查询方法，并通过Stream转换为Map
                .list()
                .stream()
                .collect(Collectors.toMap(
                        SysUser::getId,
                        Function.identity(),
                        (existing, replacement) -> existing  // 处理重复键（根据需求选择处理策略）
                ));
    }
}
